const { exec, escape } = require('../../db/mysql')
const { genPassword } = require('../utils/cryp')
// 注册控制层
const register = async (username, password) => {
    // 生成加密密码
    username = username
    password = genPassword(password)
    const sql = `
        INSERT INTO users (username, password) VALUES ('${username}', '${password}')
    `
    const insertData = await exec(sql)
    return {
        id: insertData.insertId
    }
}
const userNameFilter = async (username) => {
    const sql = `
        select id, username from users where username='${username}'
    `
    const row = await exec(sql)
    return row[0] || ''
}
// 登录控制层
const login = async (username, password) => {
    username = escape(username) // 格式化 预防sql注入
    password = genPassword(password)  // 生成加密密码
    password = escape(password) // 格式化 预防sql注入
    const sql = `select id, username from users where username=${username} and password=${password}`
    const rows = await exec(sql)
    return rows[0] || ''
}
// 查询用户信息控制层
const userInfo = async (id) => {
    const sql = `
        select id, username from users where id=${id}
    `
    const rows = await exec(sql)
    return rows[0] || ''
}

module.exports = {
    register,
    login,
    userInfo,
    userNameFilter,
}